package cn.yeziji.forum.service.impl;

import cn.yeziji.forum.service.MarkdownService;
import cn.yeziji.forum.utils.GzipUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.util.UriEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * markdown 服务实现类
 *
 * @author gzkemays
 * @since 2022/2/22 13:37
 */
@Service
public class MarkdownServiceImpl implements MarkdownService {

  @Override
  public String read(MultipartFile file) {
    String txt;
    try {
      InputStreamReader isr = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
      BufferedReader br = new BufferedReader(isr);
      StringBuilder sb = new StringBuilder();
      while ((txt = br.readLine()) != null) {
        // 读取至结尾追加 \n 换行
        txt += '\n';
        sb.append(txt);
      }
      return GzipUtils.compress(UriEncoder.encode(sb.toString()));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
